//在页面加载时候初始化蓝牙适配器
  function openBluetoothAdapter(){
  uni.openBluetoothAdapter({
    success: e => {
        console.log('初始化蓝牙成功:' + e.errMsg);
        // 初始化完毕开始搜索
        console.log("开始搜寻智能设备");
    // setTimeout(function() {
    //         console.log("开始搜寻智能设备");
    // }, 3000);
    },
    fail: e => {
        console.log('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
        uni.showToast({
          icon: "none",
          title: "初始化蓝牙失败，请打开蓝牙与定位",
          duration: 4500
      })
    }
  });
}
// 开始搜索
 function startBluetoothDevicesDiscovery(){
  uni.startBluetoothDevicesDiscovery({
    success: res => {
        console.log(res);
    },
    fail: res => {
        console.log("查找设备失败!");
       setTimeout(()=>{
        uni.showToast({
          icon: "none",
          title: "查找设备失败！",
          duration: 5000
      })
       },5000)
    }
});
}
 // 寻找到设备&&筛选设备
function onBluetoothDeviceFound(blueList){
 uni.onBluetoothDeviceFound(function (devices) {
  console.log(devices.devices[0].deviceId == "01:9A:9A:ED:93:CC")//019A9AED93CC
  if(devices.devices[0].deviceId == "01:9A:9A:ED:93:CC"){
    console.log("find",devices.devices[0],blueList);
    blueList.push(devices.devices[0])
    uni.setStorageSync('deviceId', devices.devices[0].deviceId)
    // 找到设备
}
})
}
  // 监听蓝牙状态
function onBluetoothAdapterStateChange(){
 uni.onBluetoothAdapterStateChange(function (res) {
  console.log('adapterState changed, now is', res)
  })
}
// 创建链接
function createBLEConnection(blueList,servicesList) {
  uni.createBLEConnection({
  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  deviceId:blueList[0].deviceId,
  success(res) {
    console.log("secsssssssssssssssssssssssssss-----_____________----",res);
     uni.showToast({
          icon: "none",
          title: "链接蓝牙成功!",
          duration: 3000
      })
      getBLEDeviceServices(blueList,servicesList)
  },
  // fail(res){
  //   uni.showToast({
  //     icon: "none",
  //     title: "链接蓝牙失败!请打开定位和定位",
  //     duration: 3000
  // })
  // }
})
}
// 
function getBLEDeviceServices(blueList,servicesList){
  // 后续监听特征值
  console.log("blueList,servicesList",blueList,servicesList);
  uni.getBLEDeviceServices({
  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  deviceId:blueList[0].deviceId,
  success(res) {
    console.log('device services:', res.services)
   servicesList = res.services
   console.log("servicesList",servicesList);
   servicesList.forEach((item,index)=>{
    getBLEDeviceCharacteristics(blueList[0].deviceId,item.uuid)
   })
  }
})
// }
}
//
function getBLEDeviceCharacteristics(deviceId,serviceId){
  uni.getBLEDeviceCharacteristics({
    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
    // deviceId:blueList[0].deviceId,
    deviceId:deviceId,
    // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
    // serviceId:item.uuid,
    serviceId:serviceId,
    success(res) {
    console.log('device getBLEDeviceCharacteristics:', res.characteristics)
    // characteristicId = res.characteristics
    res.characteristics.forEach(
      (item,index)=>{
        notifyBLECharacteristicValueChange(deviceId,serviceId,item.uuid)
      }
    )
    }
  })   
}
function notifyBLECharacteristicValueChange(deviceId,serviceId,characteristicId){
uni.notifyBLECharacteristicValueChange({
// uni.onBLECharacteristicValueChange({
  state: true, // 启用 notify 功能
  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  deviceId,
  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
  serviceId,
  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  characteristicId,
  success(res) {
    console.log("notifyBLECharacteristicValueChange")
    // onBLECharacteristicValueChange(deviceId,serviceId,characteristicId)
    uni.onBLECharacteristicValueChange(function (res) {
      console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
      console.log(ab2hex(res.value))
      if(ab2hex(res.value) == "706c61790d0a"){//play播放
        uni.$emit("bluePlay")
      }
      if(ab2hex(res.value) == "73746f700d0a"){//stop暂停
        uni.$emit("createInnerAudioContext_destroy")
      }
      if(ab2hex(res.value) == "6e657874776f72640d0a"){//下一首歌//nextword
        uni.$emit("bluePlayNext")
      }
      if(ab2hex(res.value) == "707265776f72640d0a"){//上一首歌//preword
        uni.$emit("bluePlayPre")
      }
      if(ab2hex(res.value) == "7072650d0a"){//上一句歌词//pre
        uni.$emit("changewords",{where:"pre"})
      }
      if(ab2hex(res.value) == "6e6578740d0a"){//下一句歌词//next
        uni.$emit("changewords",{where:"next"})
      }
      if(ab2hex(res.value) == "766f69636575700d0a"){//声音up//voiceup
        uni.$emit("blueChangevolume","up")
      }
      if(ab2hex(res.value) == "766f6964646f776e0d0a"){//声音down//voiddown
        console.log("down");
        uni.$emit("blueChangevolume","down")
      }
    })
  },
  fail(res){
    console.log("fail",res);
  }
})  
}
function ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('')
}
export {
  openBluetoothAdapter,startBluetoothDevicesDiscovery,onBluetoothDeviceFound,onBluetoothAdapterStateChange,
  createBLEConnection,getBLEDeviceServices,getBLEDeviceCharacteristics,
  notifyBLECharacteristicValueChange
}

